﻿// Copyright (c) 2014 Bryan C. O'Connell
// http://wsubi.codeplex.com/license
// Purpose: Defines the 'search' command. This command searches for and displays
// a list of scripts containing a text string specified by the user.

using System;
using System.Collections.Generic;
using Wsubi.Code.Utilities;

namespace Wsubi.Code.Commands
{
    public class Search : ICommand
    {
        public string Target { get; set; }
        public string Params { get; set; }
        public ScriptData ScriptDataStorage { get; set; }

        private ResultSet _Results;

        public string GetActionKeyword() {
            return "search";
        }

        public ResultSet Execute()
        {
            Guard.CheckForNullObject(ScriptDataStorage);

            List<string> ListOfMatches = new List<string>();
            ListOfMatches = SearchScriptsForText(Target.ToLower());
            BuildResultSet(ListOfMatches);

            return _Results;
        }

        private List<string> SearchScriptsForText(string TextToFind)
        {
            Guard.CheckForEmptyString(TextToFind);

            List<string> ListOfMatches = new List<string>();
            Dictionary<string, string> ScriptFileBin = ScriptDataStorage.ShareScriptFileBin();

            foreach (KeyValuePair<string, string> Pair in ScriptFileBin)
            {
                string ScriptText = Pair.Value.ToLower();
                if (ScriptText.Contains(TextToFind)) {
                    ListOfMatches.Add(Pair.Key);
                }
            }

            return ListOfMatches;
        }

        private void BuildResultSet(List<string> ResultsToSave)
        {
            _Results = new ResultSet();
            _Results.OutputTo = OutputsTo.Screen;

            if (ResultsToSave.Count < 1) {
                _Results.AddResult("Sorry, no scripts were found containing the text: '" + Target + "'.");
            }
            else {
                _Results.SaveResults(ResultsToSave);
            }

        }
    }
}
